<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
        <!-- <el-form-item label="名称" >
          <el-input v-model="queryParams.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mall:entry:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
        v-hasPermi="['mall:entry:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5"></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="rotationChartList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" width="200" />
      <el-table-column label="客户端类型" prop="clientType" align="center" width="250">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.client_client_type" :value="scope.row.clientType" />
        </template>
      </el-table-column>
      <el-table-column label="图标" align="center" width="150" height="100">
        <template slot-scope="scope">
          <el-image :src="scope.row.icon"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="enabled" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled" @change="handleEnabledChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="title" width="300" />
      <el-table-column label="路径" align="center" prop="path" width="300" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openUpdateImageView(scope.row)"
            v-hasPermi="['mall:entry:image:edit']">更改图片</el-button>
          <!--
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:entry:edit']">修改</el-button>
          -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mall:entry:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改快捷入口对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户端类型" prop="clientType">
          <el-select v-model="form.clientType" placeholder="客户端类型" clearable disabled>
            <el-option v-for="dict in dict.type.client_client_type" :key="dict.value"
              :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="移动端图标" v-if="form.clientType === 'APP' ? true:false">
          <el-upload action="#" list-type="picture-card" :auto-upload="false"
            :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-change="changeImg">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete">
                  <i class="el-icon-download"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete"
                  @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="是否内链" prop="internalLink">
          <el-radio-group v-model="form.internalLink">
            <el-radio v-for="dict in dict.type.is_internal_link" :key="dict.value" :label="dict.value">
              {{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跳转地址" prop="path">
          <el-input v-model="form.path" />
        </el-form-item>
        <el-form-item label="跳转参数" prop="param">
          <el-input v-model="form.param" type="textarea" placeholder="请输入跳转参数" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更改图片对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="openChangeImageView" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片地址" prop="imageUrl">
          <el-upload action="#" list-type="picture-card" :auto-upload="false"
            :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-change="changeImg">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete">
                  <i class="el-icon-download"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete"
                  @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="展示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeImage">确 定</el-button>
        <el-button @click="openChangeImageView = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listEntry,
  addEntry,
  updateEntry,

  delEntranceSet,
  handleEnabledChange,
  handleImageChange
} from "@/api/mall/entry";
import axios from "axios";
import { getToken } from "@/utils/auth";

export default {
  name: "Entry",
  dicts: ["client_client_type", "is_internal_link"],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 2,
      // 协议表格数据
      rotationChartList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createBy: undefined,
        clientType:'APP'
        // classify: undefined
      },
      // 表单参数
      form: {},
      // 轮播图
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      imageFileList: undefined,
      headers: {
        Authorization: "Bearer " + getToken(),
        "Content-Type": "multipart/form-data"
      },
      // 表单校验
      rules: {
        clientType: [
          { required: true, message: "客户端类型不能为空", trigger: "change" }
        ]
      },
      openChangeImageView: false,
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 获取轮播图列表 */
    getList () {
      this.loading = true;
      listEntry(this.queryParams).then(response => {
        this.rotationChartList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        clientType: 'APP',
        internalLink: true,
        path: undefined,
        orderNum: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加快捷入口";
      const ul = document.querySelector(".el-upload-list--picture-card");
      if (ul) {
        console.log(ul);
        ul.removeChild(ul.children[0]);
        ul.nextSibling.style.display = "block";
      }
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.form = row;
      console.log(this.form);
      this.open = true;
      this.title = "修改快捷入口";
    },
    /** 修改启用状态*/
    handleEnabledChange (row) {
      let text = row.enabled === true ? "启用" : "禁用";
      this.$modal
        .confirm('确认"' + text + '"吗？')
        .then(function () {
          return handleEnabledChange(row.id, row.enabled);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.enabled = !row.enabled;
        });
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.imageFileList) {
        const loading = this.$loading({
          lock: true,
          text: "上传中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        let formData = new FormData();
        formData.append("file", this.imageFileList[0].raw);
        axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
            headers: this.headers
          }).then(res => {
            if (res.status == 200) {
              let data = res.data;
              this.$modal.msgSuccess("上传成功");
              this.form.icon = data.data.url;
              this.form.imageId = data.data.id;
              if (this.form.id != undefined) {
                updateEntry(this.form.id, this.form).then(response => {
                  console.log(this.form);
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addEntry(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            } else {
              this.$message.error("上传文件失败" + res.data.msg);
            }
          }).finally(res => {
            loading.close();
          });
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const id = row.id;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delEntranceSet(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 删除图片
    handleRemove (file, fileList) {
      const ul = document.querySelector(".el-upload-list--picture-card");
      ul.removeChild(ul.children[0]);
      ul.nextSibling.style.display = "block";
      console.log(file, fileList);
    },
    // 预览图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.raw.url;
      this.dialogVisible = true;
    },
    // 上传图片
    changeImg (file, fileList) {
      const ul = document.querySelector(".el-upload-list--picture-card");
      ul.nextSibling.style.display = "none";
      console.log(file, fileList);
      this.imageFileList = fileList;
    },
    openUpdateImageView(row){
      this.imageFileList = [];
      this.title = "更换图片";
      this.openChangeImageView = true;
      this.form = { ...row };
    },
    //更换图片
    changeImage(){
      if(!this.form.orderNum){
        this.$modal.msgError("请填写排序编号");
        return;
      }

      if (!this.imageFileList) {
        this.$modal.msgError("请选择图片");
        return;
      }

      const _this = this;
      this.$modal.confirm("确认更换轮播图图片吗？").then(function () {
        const loading = _this.$loading({
          lock: true,
          text: "上传中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        let formData = new FormData();
        formData.append("file", _this.imageFileList[0].raw);
        axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
          headers: _this.headers
        }).then(res => {
          if (res.status == 200) {
            let data = res.data;
            if (data.code == 200) {
              const changeImageData = {
                imageId: data.data.id,
                imageUrl: data.data.url,
                countdown: _this.form.countdown,
                orderNum: _this.form.orderNum
              }
              handleImageChange(_this.form.id, changeImageData).then(res=>{
                _this.$modal.msgSuccess("更换成功");
                _this.getList();
                _this.openChangeImageView = false;
              });
            } else {
              _this.$message.error("上传文件失败" + res.data.msg);
            }
          }
        }).finally(res => {
          loading.close();
        });
      }).catch(function(err) {
        console.log(err)
        _this.$modal.msgError("更换图片出错");
      });
    },
  }
};
</script>
